package admin

import (
	"github.com/dchest/captcha"
	"github.com/gin-gonic/gin"
	"go_my_framework/app/service"
	"go_my_framework/util/base"
	captcha2 "go_my_framework/util/captcha"
	"net/http"
)

type LoginForm struct {
	Username string `form:"username" binding:"required" zh:"用户名"`
	Password string `form:"password" binding:"required" zh:"密码"`
}

// 登录
func Login(c *gin.Context) {
	if c.Request.Method == "GET" {
		c.HTML(http.StatusOK, "/admin/login/login", gin.H{})
	} else {
		// 表单数据校验
		var req LoginForm
		if err := c.ShouldBind(&req); err != nil {
			base.Error(c, err.Error(), nil)
			return
		}
		// 账号密码验证
		svc := service.AdminService{}
		err := svc.SignIn(c, req.Username, req.Password)
		if err != nil {
			base.Error(c, err.Error(), nil)
			return
		}
		base.Success(c, "登录成功", nil)
	}
}

// 退出登录
func Logout(c *gin.Context) {
	svc := service.AdminService{}
	_ = svc.ClearAdminSession(c)
	base.Redirect(c, http.StatusFound, "/admin/login/login")
}

// 创建验证码
func BuildCaptcha(c *gin.Context) {
	length := captcha.DefaultLen
	captchaId := captcha.NewLen(length)

	var response = make(map[string]string)
	response["id"] = captchaId                          // 验证码Id
	response["path"] = "/captcha/" + captchaId + ".png" // 验证码图片url
	base.Success(c, "", response)
	return
}

// 获取验证码图片
func GetCaptchaImg(c *gin.Context) {
	captcha2.ServeHTTP(c.Writer, c.Request)
}

// 校验图像验证码
func VerifyCaptcha(c *gin.Context) {
	id := c.PostForm("id")
	capt := c.PostForm("capt")
	if id == "" || capt == "" {
		c.String(http.StatusBadRequest, "参数错误")
	}
	if captcha.VerifyString(id, capt) {
		base.Success(c, "验证成功", nil)
		return
	} else {
		base.Error(c, "验证失败", nil)
		return
	}
}

func NotFound(c *gin.Context) {
	c.HTML(http.StatusOK, "not_found.html", gin.H{})
}